﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using Biz.EF.Gateway.Monitor;
using Biz.EF.Platform;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    public class DownlineCmdInstructionBoth
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DownlineCmdInstructionBoth));

        public static void Gen1011CmdToGateway(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {
            try
            {
                var cmds = pCtx.现场机系统时间.Where(t => t.执行结果标志ID == 601).Take(1000).ToList();
                foreach (var downcmd in cmds)
                {
                    downcmd.执行结果标志ID = 602;

                    var cn = "";
                    if (downcmd.执行事项 != null && downcmd.执行事项.Contains("提取"))
                        cn = "1011";
                    else if (downcmd.执行事项 != null && downcmd.执行事项.Contains("设置"))
                        cn = "1012";
                    if (string.IsNullOrEmpty(cn)) continue;
                    //var port = CommonInformation.GetLetportById(downcmd.设备信息ID);
                    var mn = Regex.Match(downcmd.设备MN号, "[0-9A-Za-z]{24}").Value;
                    if (string.IsNullOrEmpty(mn)) continue;

                    var cp = "";
                    if (cn.Equals("1012"))
                    {
                        if (downcmd.设置时间 == null)
                        {
                            downcmd.设置时间 = DateTime.Now;
                        }
                        cp = "SystemTime=" + downcmd.设置时间.Value.ToString("yyyyMMddHHmmss");
                    }
                    if (downcmd.QN == null)
                    {
                        downcmd.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    }

                    var resultStr = "QN=" + downcmd.QN + ";ST=32;" + "CN=" + cn + ";PW=123456" + ";MN=" + mn
                                        + ";Flag=5;CP=&&" + cp + "&&";
                    var result = Crc.WrapByCrc(resultStr, "monitor");
                    var now = DateTime.Now;
                    send_ctr_cmd cmd = new send_ctr_cmd
                    {
                        cn = cn,
                        mn = mn,
                        qn = downcmd.QN,
                        is_sent = false,
                        send_string = result,
                        sent_time = now,
                        send_time = now
                    };
                    gCtx.send_ctr_cmd.Add(cmd);
                    gCtx.SaveChanges();
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }


    }
}
